#pragma once

#include"Log.hpp"
#include <cstdio>
#include <functional>
#include<iostream>
#include<string>
#include<cstring>
#include<arpa/inet.h>
#include<netinet/in.h>
#include <strings.h>
#include<sys/socket.h>
#include<sys/types.h>
#include <unistd.h>
#include"InetAddr.hpp"
using namespace LogModule;
const int defaultfd = -1;
using func_t = std::function<std::string(const std::string&, InetAddr &)> ;

class UdpServer
{
public:
    //  传端口 任务 ip地址默认设置
    UdpServer(uint16_t port, func_t func)
    :   _sockfd(defaultfd),
        _port(port),
        _isrunning(false),
        _func(func)    
    {

    }

    void Init()
    {
        //创建套接字 
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error!";
        }
        LOG(LogLevel::INFO)<<"socket success, socket: "<<_sockfd;

        //  绑定socket信息  ip和端口 
        struct sockaddr_in local;
        //bzero(&local, sizeof(local));
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n < 0)
        {
            LOG(LogLevel::FATAL) <<"bind error";
            exit(2);
        }
        LOG(LogLevel::INFO)<<"bind success, socked: "<<_sockfd;
    }
    
    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            // 收消息
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
            if(s > 0)
            {
                InetAddr client(peer);
                buffer[s] = 0;
                std::string result = _func(buffer, client);

                sendto(_sockfd, result.c_str(), result.size(), 0,(struct sockaddr*)&peer, len);

            }

        }
    }

    ~UdpServer()
    {

    }
private:
    int _sockfd;
    uint16_t _port;
    bool _isrunning;
    func_t _func;
};